import React, { Component } from "react"
import { withRouter } from "react-router"
import styles from './equip.less'
import { userEquipList } from '@/services'
import Confirm from '@/utils/confirm'
import { userEquipUnBind } from '@/services'
import Toast from '@/utils/toast'
import md5 from 'js-md5';
class MyEquip extends Component {

  constructor(props){
    super(props);
    this.state = {
      recList: [],
      search: ''
    }
  }

  async componentDidMount(){
    try {
      const data = await userEquipList();
      if(data.code === 200){
        this.setState({ recList: data.data })
      }
    } catch (error) {
      console.log(error);
    }
  }

  unbind = (code) => {
    Confirm({ title: '删除提示', text: `是否解绑设备<span style="color: #EA3A12">${code}</span>` }).then(()=>{
      userEquipUnBind({ equipCode: code }).then(data=>{
        if(data.code==200){
          Toast.success('操作成功');
          this.componentDidMount();
        }
      }).catch (error=>{
        console.log(error);
      })
    })
  }

  onChange = (e) => {
    this.setState({
      search: e.target.value
    })
  }

  toCarDetail = (data) => {
    this.props.history.push(`carDetail?equipCode=${data.equipCode}&source=selfpage&token=${md5(data.equipCode+'selfpage'+'s$31d0dl1!~93-kHj^S')}`)
  }

  handleSearch = async() => {
    this.props.history.push('bindequip')
  }
  
  render(){
    return (
      <div>
        <div className={styles.header}>
          <img className={styles.top_bg} src={require('../assets/img/home/top_bg.png')} />
          <div className={styles.content}>
            <img onClick={()=>{ this.props.history.go(-1) }} className={styles.back} src={require('../assets/img/back.png')} />
            设备管理
          </div>
        </div>
        <div className={styles.container}>
          <div className={styles.search} onClick={this.handleSearch}>
            <input placeholder="绑定设备" className={styles.search_input} value={this.state.search} onChange={this.onChange}  />
            <img src={require('../assets/img/equip/search.png')} className={styles.search_icon} />
          </div>
          <div className={styles.title}>我的设备</div>
          <div className={styles.list}>
            {this.state.recList.map((data)=>(
              <div onClick={()=>{ this.toCarDetail(data) }} className={styles.item} key={data.equipCode} >
                <div className={styles.item_left}>{data.equipCode}</div>
                <div onClick={(e)=>{ e.stopPropagation(); this.unbind(data.equipCode) }} className={styles.item_right_bind}>解绑</div>
              </div>
            ))}
          </div>
        </div>
        <div className={styles.bottom} onClick={()=>{ this.props.history.replace('/') }}>
          <div className={styles.bottom_btn}>返 回</div>
        </div>
      </div>
    )
  }
}
export default withRouter(MyEquip)